//
//  V2CategoriesViewController.m
//  V2EX
//
//  Created by 花菜ChrisCai on 2016/6/11.
//  Copyright © 2016年 Chris. All rights reserved.
//

#import "V2CategoriesViewController.h"
#import "V2TopicModel.h"
#import "V2TopicCell.h"




@interface V2CategoriesViewController ()<UITableViewDelegate,UITableViewDataSource>
/** 左边表格模型数据 */
@property(nonatomic, strong) NSArray *topicsArray;
/** 右边表格数据 */
@property(nonatomic, strong) NSArray *sectionDataArray;
/** 右边菜单控件 */
@property (weak, nonatomic) IBOutlet UITableView *sectionTableView;
@property (weak, nonatomic) IBOutlet UITableView *CategoryTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftMarginConst;
@property (weak, nonatomic) IBOutlet UIButton *coverButton;
@end
#define V2SelectedSection self.sectionDataArray[[self.sectionTableView indexPathForSelectedRow].row];
static NSString *const V2CategoryCellIdentifier = @"V2CategoryCellIdentifier";
static NSString * const V2SectionCellIdentifier = @"V2SectionCellIdentifier";
static CGFloat const kRightMenuWidth = 80.0f;
@implementation V2CategoriesViewController
#pragma mark -
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化导航栏
    [self setupNav];
    // 初始化表格控件
    [self setupTableView];
    // 初始化刷新控件
    [self setupRefresh];
    // 添加侧滑手势
    [self setupGestureRecognizer];
}
#pragma mark -
#pragma mark - 懒加载
- (NSArray *)sectionDataArray
{
    if (!_sectionDataArray) {
        _sectionDataArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"nodes.plist" ofType:nil]];
    }
    return _sectionDataArray;
}
- (NSArray *)topicsArray
{
    if (!_topicsArray) {
        _topicsArray =  [NSArray array];
        
    }
    return _topicsArray;
}

/**
 *  初始化导航栏
 */
- (void)setupNav
{
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem gk_itemWithImage:[UIImage imageNamed:@"navi_dot"] highImage:nil target:self action:@selector(rightClick:)];
}


/**
 *  初始化表格控件
 */
- (void)setupTableView
{
    // 取消系统默认内边距
    self.automaticallyAdjustsScrollViewInsets = NO;
    // 设置内间距
    self.CategoryTableView.contentInsetTop = 64;
    self.sectionTableView.contentInsetTop = self.CategoryTableView.contentInsetTop;
    
    // 注册cell
    [self.CategoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([V2TopicCell class]) bundle:nil] forCellReuseIdentifier:V2CategoryCellIdentifier];
    [self.sectionTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:V2SectionCellIdentifier];
    // 计算行高
    self.CategoryTableView.estimatedRowHeight = 70;
    self.CategoryTableView.rowHeight = UITableViewAutomaticDimension;
    
}

/**
 *  初始化刷新控件
 */
- (void)setupRefresh
{
    self.CategoryTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    [self tableView:self.sectionTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [self.sectionTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
}

- (void)setupGestureRecognizer
{
    UIScreenEdgePanGestureRecognizer *rightPan = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(rightPan:)];
    rightPan.edges = UIRectEdgeRight;
    [self.view addGestureRecognizer:rightPan];
}
#pragma mark -
#pragma mark - 事件处理
- (void)rightClick:(UIButton *)btn
{
        btn.selected = !btn.selected;
        if (btn.selected) {
            self.coverButton.hidden = NO;
            self.leftMarginConst.constant = -kRightMenuWidth;
        } else {
            self.leftMarginConst.constant = 0;
            self.coverButton.hidden = YES;
        }
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (IBAction)coverButtonClick:(UIButton *)sender
{
    sender.hidden = YES;
    self.leftMarginConst.constant =0;
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    UIButton *btn = (UIButton *)self.navigationItem.rightBarButtonItem.customView.subviews.firstObject;
    btn.selected = NO;
}


- (void)loadNewData
{
    NSDictionary *dict = V2SelectedSection;
    self.navigationItem.title = dict[@"name"];
    V2Log(@"%@",[V2HTTPBaseUrl stringByAppendingString:dict[@"nodeURL"]]);
    [GKNetworkingManager getHtmlCodeWithUrlString:dict[@"nodeURL"] success:^(NSData *data) {
        self.topicsArray =  [V2HTMLHelper dataToObject:data];
        [self.CategoryTableView reloadData];
        [self.CategoryTableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [self.CategoryTableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}

- (void)rightPan:(UIScreenEdgePanGestureRecognizer *)pan
{
    CGFloat progress = ABS([pan translationInView:self.view].x / kRightMenuWidth);
   
    if (progress > 1) {
        progress = 1;
    }
    if (pan.state == UIGestureRecognizerStateBegan) {
    }else if (pan.state == UIGestureRecognizerStateChanged){
       self.leftMarginConst.constant = - kRightMenuWidth * progress;
    }else {
        if (progress > 0.5) {
            self.leftMarginConst.constant = - kRightMenuWidth;
            [UIView animateWithDuration:0.25 animations:^{
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished) {
                self.coverButton.hidden= NO;
            }];
        }else {
            self.leftMarginConst.constant = 0;
            [UIView animateWithDuration:0.25 animations:^{
               [self.view layoutIfNeeded];
            } completion:^(BOOL finished) {
                self.coverButton.hidden= YES;
            }];
        }
    }


}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (tableView == self.CategoryTableView) {
        return self.topicsArray.count;
    } else {
        return self.sectionDataArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.CategoryTableView) {
        
        V2TopicCell *cell = [tableView dequeueReusableCellWithIdentifier:V2CategoryCellIdentifier];
        cell.model = self.topicsArray[indexPath.row];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:V2SectionCellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.text = self.sectionDataArray[indexPath.row][@"name"];
        cell.textLabel.highlightedTextColor = [UIColor blueColor];
        return cell;
    }
    
}

#pragma mark -
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.sectionTableView) {
        [self.CategoryTableView.mj_header beginRefreshing];
        [self coverButtonClick:self.coverButton];
    }else {
        V2LogFunc
    }

}


@end
